from app import db
from app.models.user import User
from sqlalchemy.exc import SQLAlchemyError
import logging

"""
获取用户
"""
def get_user_by_username(username):
    try:
        return User.query.filter_by(username=username).first()
    except SQLAlchemyError as e:
        logging.error(f"查询用户{username}失败: {str(e)}")
        return None


"""
创建用户
"""
def create_user(username, password, **kwargs):
    try:
        user = User(username=username, password=password, **kwargs)
        db.session.add(user)
        db.session.commit()
        return user
    except SQLAlchemyError as e:
        db.session.rollback()
        logging.error(f"创建用户{username}失败: {str(e)}")
        return None

"""
查询用户信息返回用户名，头像，昵称，手机号，邮箱
"""
def get_user_info_by_id(user_id):
    try:
        user = User.query.filter_by(id=user_id).first()
        if user:
            return {
                'username': user.username,
                'avatar': user.avatar,
                'nickname': user.nickname,
                'phone': user.phone,
                'email': user.email
            }
        else:
            return None
    except SQLAlchemyError as e:
        logging.error(f"查询用户{user_id}信息失败:{str(e)}")

"""
用户修改信息
"""
def update_user_info_by_id(user_id, data):
    try:
        user = User.query.filter_by(id=user_id).first()
        if user:
            for key, value in data.items():
                setattr(user, key, value)
            db.session.commit()

            return {
                'username': user.username,
                'avatar': user.avatar,
                'nickname': user.nickname,
                'phone': user.phone,
                'email': user.email
            }
        else:
            return None
    except SQLAlchemyError as e:
        db.session.rollback()
        logging.error(f"更新用户{user_id}信息失败:{str(e)}")

"""
用户修改密码
"""
def update_user_password_by_id(user_id, password):
    try:
        user = User.query.filter_by(id=user_id).first()
        if user:
            user.password = password
            db.session.commit()
            return True
        else:
            return False
    except SQLAlchemyError as e:
        db.session.rollback()
        logging.error(f"更新用户{user_id}密码失败:{str(e)}")